<template>
  <mci-label class="py-5"> 数据结构 </mci-label>
  <div class="max-h-500 min-h-200 mt-8" style="width: 100%; overflow: auto">
    <div class="grid gap-x-2 gap-y-4 grid-cols-3 bg-fill-2">
      <!-- 标题行 -->
      <div class="bg-fill-0 px-10 py-8">
        <mci-text model-value="解析字段" />
      </div>
      <div class="bg-fill-0 p, px-10 py-8">
        <mci-text model-value="字段重命名" />
      </div>
      <div class="bg-fill-0 px-10 py-8">
        <mci-text model-value="字段类型" />
      </div>
    </div>
    <!-- 字段行 -->
    <div v-for="(item, index) in listDatas" :key="index" class="grid gap-x-2 gap-y-4 grid-cols-3">
      <div class="bg-fill-0 px-10 py-6">
        <MciCheckbox v-model="item.checked" :label="item.varName" @change="checkChange" />
      </div>
      <div class="bg-fill-0 px-10 py-6">
        <mci-input
          v-model="item.varLabel"
          :min="INPUT_MIN_DATA_NAME"
          :max="INPUT_MAX_DATA_NAME"
          @update:modelValue="updateValue"
        />
      </div>
      <div class="bg-fill-0 px-10 py-6">
        <mci-select v-model="item.varType" :list="options">
          <mci-option
            v-for="option in fieldTypeOptions"
            :key="option.dictCode"
            :label="option.dictName"
            :value="option.dictCode"
          />
        </mci-select>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { MciSelect, MciOption, MciCheckbox, MciInput, MciText, MciLabel } from '@/components/base';
import { INPUT_MAX_DATA_NAME, INPUT_MIN_DATA_NAME, ValueTypeDict } from './data';
import { useDictStore } from '@/store/dict';

const props = defineProps<{
  data: any;
}>();
const emit = defineEmits(['change']);

watch(
  [() => props.data],
  ([newData]) => {
    initData(newData);
  },
  { deep: true }
);
const dictStore = useDictStore();

const listDatas = ref<any[]>([]);
const fieldTypeOptions = ref<any[]>([]);
fieldTypeOptions.value = dictStore.fieldType || [];

const initData = (data: any) => {
  if (data) {
    const keys = Object.keys(data);
    listDatas.value = keys.map((item) => {
      let jsType: any = typeof data[item];
      switch (jsType) {
        case 'number':
          if (jsType === 'number') {
            jsType = Number.isInteger(data[item]) ? 'int' : 'float';
          }
          break;
        default:
          jsType = 'string';
          break;
      }

      return {
        varName: item,
        varLabel: item,
        varType: ValueTypeDict[jsType],
        // initValue: null, // data[item],
        checked: true
      };
    });
  }
};

// 数据类型选择
const options = ref<any>([]);

// 选中改变回调
const checkChange = () => {
  emit('change');
};
// 字段名修改回调
const updateValue = () => {
  emit('change');
};

const getData = () => {
  return listDatas.value;
};

defineExpose({
  getData
});
</script>
